import os
import shutil
import json

from vulcanus.log.log import LOGGER
from zeus.operation_service.app.constant import SECURITY_MANAGE_PATH
from zeus.operation_service.app.core.framework.task.task_factory.health_check_task import HealthCheckTask
from zeus.operation_service.app.core.framework.task.task_result.result_generator.node_manage.item_security_manage_generator import \
    ItemSecurityManageGenerator
from zeus.operation_service.app.core.framework.task.task_result.result_generator.node_manage.node_security_manage_generator import \
    NodeSafeManageGenerator
from zeus.operation_service.app.core.framework.task.task_result.result_generator.health_check.report_generator import ReportContext
from zeus.operation_service.app.core.framework.common.constant import TaskType
from zeus.operation_service.app.core.framework.common.result_code import ItemResultCode
from zeus.operation_service.app.proxy.asset import AssetProxy
from zeus.operation_service.app.proxy.host import HostProxy


class SecurityManageTask(HealthCheckTask):
    def __init__(self, task_param):
        super().__init__(task_param)
        self.task_type = TaskType.SECURITY_MANAGE
        self.recover = task_param.get('recover', False)

    def _post_success(self):
        LOGGER.warning(f"post_success: task name is {self.task_name}")
        report_path = os.path.join(SECURITY_MANAGE_PATH, self.task_id)

        report_raw_data = self.get_security_manage_report_data()
        report_context = ReportContext()
        report_context.generator = ItemSecurityManageGenerator(report_path)
        report_context.generate_report(report_raw_data)
        report_context.generator = NodeSafeManageGenerator(report_path)
        report_context.generate_report(report_raw_data)
        zip_name = f"{'_'.join(self.task_name.split('_')[:-2])}.zip"
        shutil.make_archive(report_path, "zip", report_path)
        shutil.move(f"{report_path}.zip", os.path.join(report_path, zip_name))

    def get_security_manage_report_data(self):
        return self.get_health_check_report_data()

    class TaskYaml(HealthCheckTask.TaskYaml):
        def __init__(self, task_params):
            super().__init__(task_params)
            self.workflow_template = "health_check_workflow.yml"
            self.task_type = TaskType.SECURITY_MANAGE
            self.recover = task_params.get('recover', False)

        def addition_config(self, config_json, task_assets, task_case_node):
            config_json['recover'] = self.recover
            # config_json 带上每个节点错误的巡检，用于安全恢复
            hosts_error = dict()
            for task_host in self.task_hosts:
                host = HostProxy().get_host_by_id(task_host["host_id"])
                host_ip = host.get("host_ip")
                node_result = AssetProxy().get_health_check_result_item(self.task_id, task_host['host_id']).all()
                error_list = []
                for result_item in node_result:
                    error_level = json.loads(result_item.task_result)[0]["ErrLevel"]
                    if int(error_level) == ItemResultCode.ITEM_RECOVER.code:
                        asset_item = AssetProxy().get_asset_item_by_id(result_item.health_check_asset_item_id)
                        error_list.append(asset_item.item_path)
                        AssetProxy().del_health_check_result_item(result_item.result_id)
                hosts_error[host_ip] = error_list
            config_json['hosts_error'] = hosts_error
            return config_json
